/**
 * dva 中 的model
 */
import { queryList } from '../services/demos';

export default {
  namespace: 'javascript', // model 的命名空间，区别于其他 model 的 state, effect等;

  state: {
    list: [
      { title: 'aaa' },
      { title: 'bbb' },
      { title: 'ccc' },
    ],
    loading: false,
    currentDemo: undefined,
    name: 'sunxt',
  },

  // effects 负责和服务端交互的网络请求，请求后调用 reducers, 进而改变 state
  effects: {
    // 获取，添加 List
    *getList({ payload }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      // 1. 发出请求， 异步获取服务端数据;
      const response = yield call(queryList, payload);
      // 2. 调用 reducers
      yield put({
        type: 'updateList',
        // type: 'appendList',
        payload: Array.isArray(response) ? response : [],
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },
  },

  // reducers: 同步操作， 改变state
  reducers: {
    appendList(state, action) {
      return {
        ...state,
        list: state.list.concat(action.payload),
      };
    },
    updateList(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    changeLoading(state, action) {
      return {
        ...state,
        loading: action.payload,
      };
    },
    changeName(state, action) {
      // console.log(action);
      const { name } = action.payload;
      return {
        ...state,
        name,
      };
    },
  },
};
